package com.yshebkb.sulp.service;

import com.yshebkb.sulp.config.AppProperties;
import com.yshebkb.sulp.dao.RoleMapper;
import com.yshebkb.sulp.dao.UserMapper;
import com.yshebkb.sulp.entity.Role;
import com.yshebkb.sulp.entity.User;
import com.yshebkb.sulp.exception.AppException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author yshebkb
 * create at 2018/8/25 13:06
 */
@Service
public class RoleService {
    @Autowired
    private AppProperties appProperties;

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    public List<Role> findRolesByUsername(String username) {
        User user = userMapper.findByName(username);
        return user.getRoles();
    }

    public List<Role> findAll() {
        return roleMapper.findAll();
    }

    public int updateUser(Role role) {
        return roleMapper.updateByPrimaryKeySelective(role);
    }

    public void deleteById(Long id) {
        Role dbRole = roleMapper.selectByPrimaryKey(id);
        if (dbRole == null) {
            throw new AppException(0, "用户不存在");
        }
        if (dbRole.getName().equals(appProperties.getSysAdmin())){
            throw new AppException(0, "管理员不允许删除");
        }
        roleMapper.deleteByPrimaryKey(id);
    }
}
